﻿@model OrderListModel
@{
    var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    //page title
    ViewBag.Title = T("Admin.Orders").Text;
}

@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.Orders")
        </div>
        <div class="options">
            @if (!Model.IsLoggedInAsVendor)
            {
                //a vendor cannot export/import orders
                <a href="@Url.Action("ExportXmlAll")" class="k-button">@T("Admin.Common.ExportToXml.All")</a>
                <input type="button" id="exportxml-selected" class="k-button" value="@T("Admin.Common.ExportToXml.Selected")" />
                <a href="@Url.Action("ExportExcelAll")" class="k-button">@T("Admin.Common.ExportToExcel.All")</a>
                <input type="button" id="exportexcel-selected" class="k-button" value="@T("Admin.Common.ExportToExcel.Selected")" />
            }
            <input type="button" id="pdf-invoice-selected" class="k-button" value="@T("Admin.Orders.PdfInvoice.Selected")" />
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.CustomerEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.CustomerEmail)
            </td>
        </tr>
        <tr @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("OrderStatusId", Model.AvailableOrderStatuses)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.PaymentStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("PaymentStatusId", Model.AvailablePaymentStatuses)
            </td>
        </tr>
        <tr @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.ShippingStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("ShippingStatusId", Model.AvailableShippingStatuses)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StoreId):
            </td>
            <td class="adminData">
                @Html.DropDownList("StoreId", Model.AvailableStores)
            </td>
        </tr>
        <tr @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.VendorId):
            </td>
            <td class="adminData">
                @Html.DropDownList("VendorId", Model.AvailableVendors)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.WarehouseId):
            </td>
            <td class="adminData">
                @Html.DropDownList("WarehouseId", Model.AvailableWarehouses)
            </td>
        </tr>
       <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderGuid):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.OrderGuid)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.GoDirectlyToNumber)
                <input type="submit" name="go-to-order-by-number" class="k-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnSearch" class="k-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
     <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                <div id="orders-grid"></div>

                <script>
                    $(document).ready(function() {
                        $("#orders-grid").kendoGrid({
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("OrderList", "Order"))",
                                        type: "POST",
                                        dataType: "json",
                                        data: additionalData
                                    }
                                },
                                schema: {
                                    data: "Data",
                                    total: "Total",
                                    errors: "Errors"
                                },
                                requestEnd: function (e) {
                                    if (e.type == "read") {
                                        var response = e.response;
                                        if (response) {
                                            //store extra data
                                            reportAggregates = e.response["ExtraData"];
                                        }
                                    }
                                },
                                error: function(e) {
                                    display_kendoui_grid_error(e);
                                    // Cancel the changes
                                    this.cancelChanges();
                                },
                                pageSize: @(defaultGridPageSize),
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true
                            },
                            pageable: {
                                refresh: true,
                                pageSizes: [@(gridPageSizes)]
                            },
                            editable: {
                                confirmation: false,
                                mode: "inline"
                            },
                            scrollable: false,
                            dataBound: onDataBound,
                            columns: [
                                {
                                    field: "Id",
                                    headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                    headerAttributes: { style: "text-align:center" },
                                    attributes: { style: "text-align:center" },
                                    template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                    width: 50
                                },
                                {
                                    field: "Id",
                                    title: "@T("Admin.Orders.Fields.ID")",
                                width: 50
                                },
                                @if (!Model.IsLoggedInAsVendor)
                                {
                                    //a vendor does not have access to this functionality
                                    <text>{
                                    field: "OrderStatus",
                                title: "@T("Admin.Orders.Fields.OrderStatus")",
                            width: 200
                        },</text>
                                }
                                {
                                    field: "PaymentStatus",
                                    title: "@T("Admin.Orders.Fields.PaymentStatus")",
                                    width: 200
                                },
                                @if (!Model.IsLoggedInAsVendor)
                                {
                                    //a vendor does not have access to this functionality
                                    <text>{
                                    field: "ShippingStatus",
                                        title: "@T("Admin.Orders.Fields.ShippingStatus")",
                            width: 200
                        },</text>
                                }
                                {
                                    field: "CustomerEmail",
                                    title: "@T("Admin.Orders.Fields.Customer")",
                                    width: 300,
                                    template: '#=CustomerFullName# (#=CustomerEmail#)'
                                },
                                {
                                    field: "StoreName",
                                    title: "@T("Admin.Orders.Fields.Store")",
                                    width: 200
                                }, {
                                    field: "CreatedOn",
                                    title: "@T("Admin.Orders.Fields.CreatedOn")",
                                    width: 200,
                                    type: "date",
                                    format: "{0:G}"
                                },
                                @if (!Model.IsLoggedInAsVendor)
                                {
                                    //a vendor does not have access to this functionality
                                    <text>{
                                    field: "OrderTotal",
                                    title: "@T("Admin.Orders.Fields.OrderTotal")",
                                    width: 200,
                                    footerTemplate: '<div><strong>@T("Admin.Orders.Report.Summary"):</strong></div>' +
                                                         '<div>@T("Admin.Orders.Report.Profit"): <span id=\"aggregator-profit-block\"></span></div>' +
                                                         '<div>@T("Admin.Orders.Report.Shipping"): <span id=\"aggregator-shipping-block\"></span></div>' +
                                                         '<div>@T("Admin.Orders.Report.Tax"): <span id=\"aggregator-tax-block\"></span></div>' +
                                                         '<div>@T("Admin.Orders.Report.Total"): <span id=\"aggregator-total-block\"></span></div>'
                                },</text>
                                }
                                {
                                    field: "Id",
                                    title: "@T("Admin.Common.Edit")",
                                    width: 100,
                                    template: '<a href="Edit/#=Id#">@T("Admin.Common.Edit")</a>'
                                }
                            ]
                        } );
                    });
                </script>

                <script type="text/javascript">

                    var selectedIds = [];
                    var reportAggregates = "";

                    $(document).ready(function () {

                        //search button
                        $('#btnSearch').click(function () {
                            //search
                            var grid = $('#orders-grid').data('kendoGrid');
                            grid.dataSource.page(1); //new search. Set page size to 1
                            grid.dataSource.read();
                            //clear selected checkboxes
                            $('.checkboxGroups').attr('checked', false).change();
                            selectedIds = [];
                            return false;
                        });

                        $("#@Html.FieldIdFor(model => model.CustomerEmail)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#btnSearch").click();
                                return false;
                            }
                        });
                        
                        $('#mastercheckbox').click(function () {
                            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                        });

                        //wire up checkboxes.
                        $('#orders-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
                            var $check = $(this);
                            if ($check.is(":checked") == true) {
                                var checked = jQuery.inArray($check.val(), selectedIds);
                                if (checked == -1) {
                                    //add id to selectedIds.
                                    selectedIds.push($check.val());
                                }
                            }
                            else {
                                var checked = jQuery.inArray($check.val(), selectedIds);
                                if (checked > -1) {
                                    //remove id from selectedIds.
                                    selectedIds = $.grep(selectedIds, function (item, index) {
                                        return item != $check.val();
                                    });
                                }
                            }
                            updateMasterCheckbox();
                        });
                    });

                    function additionalData() {
                        return {
                            StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                            EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                            CustomerEmail: $('#@Html.FieldIdFor(model => model.CustomerEmail)').val(),
                            OrderStatusId: $('#@Html.FieldIdFor(model => model.OrderStatusId)').val(),
                            PaymentStatusId: $('#@Html.FieldIdFor(model => model.PaymentStatusId)').val(),
                            ShippingStatusId: $('#@Html.FieldIdFor(model => model.ShippingStatusId)').val(),
                            StoreId: $('#@Html.FieldIdFor(model => model.StoreId)').val(),
                            VendorId: $('#@Html.FieldIdFor(model => model.VendorId)').val(),
                            WarehouseId: $('#@Html.FieldIdFor(model => model.WarehouseId)').val(),
                            OrderGuid: $('#@Html.FieldIdFor(model => model.OrderGuid)').val()
                        };
                    }

                    function onDataBound(e) {

                        $('#orders-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                            var currentId = $(this).val();
                            var checked = jQuery.inArray(currentId, selectedIds);
                            //set checked based on if current checkbox's value is in selectedIds.
                            $(this).attr('checked', checked > -1);
                        });

                        updateMasterCheckbox();

                        //update order totals summary
                        if (reportAggregates != "") {
                            for (var key in reportAggregates) {
                                $('#aggregator-profit-block').text(reportAggregates['aggregatorprofit']);
                                $('#aggregator-shipping-block').text(reportAggregates['aggregatorshipping']);
                                $('#aggregator-tax-block').text(reportAggregates['aggregatortax']);
                                $('#aggregator-total-block').text(reportAggregates['aggregatortotal']);
                            }
                        }
                    }
                    
                    function updateMasterCheckbox() {
                        var numChkBoxes = $('#orders-grid input[type=checkbox][id!=mastercheckbox]').length;
                        var numChkBoxesChecked = $('#orders-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
                        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                    }
                </script>
            </td>
        </tr>
    </table>
}


@*export selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportXmlSelected", "Order", FormMethod.Post, new { id = "export-xml-selected-form" }))
{
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">

    $(document).ready(function () {
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-xml-selected-form #selectedIds').val(ids);
            $('#export-xml-selected-form').submit();
            return false;
        });
    });

</script>

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportExcelSelected", "Order", FormMethod.Post, new { id = "export-excel-selected-form" }))
{
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">

    $(document).ready(function () {
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-excel-selected-form #selectedIds').val(ids);
            $('#export-excel-selected-form').submit();
            return false;
        });
    });

</script>

@*Print packaging slips selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("PdfInvoiceSelected", "Order", FormMethod.Post, new { id = "pdf-invoice-selected-form" }))
{
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">

    $(document).ready(function () {
        $('#pdf-invoice-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#pdf-invoice-selected-form #selectedIds').val(ids);
            $('#pdf-invoice-selected-form').submit();
            return false;
        });
    });

</script>
